//
//  SingleDetailTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/7.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HandyJSON
import Photos

class SingleDetailTableViewController: BaseTableViewController {
    
    var id = 0
    
    var startTime = ""
    var endTime = ""
    var name = ""
    var img = ""
    
    var dataArray = [ListModel]()
    
    var isScreenHot = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        
        self.title = "单品明细"
        self.getOrderStatisDetail()
        self.setRightBarButton(title: "导出", imageName: "", action: #selector(rightBarButtonMethod), titleColor: "#000000")
    }
    
    @objc func rightBarButtonMethod(){

        self.checkPhoto(authorizedBlock: {
            self.isScreenHot = true
            self.tableView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: false)
            self.tableView.reloadData()
            PKhud.showProgress(title: "正在生成报表~")
            Utils.DispatchAfter(after: 2, handler: {
                let image = Screenshot.getTableViewimage(self.tableView)
                UIImageWriteToSavedPhotosAlbum(image!, self, #selector(self.image(image:didFinishSavingWithError:contextInfo:)), nil)
            })
        }) {
            PKhud.showText(text: "请在设置中允许访问相册~")
            Utils.DispatchAfter(after: 2, handler: {
                let url = URL.init(string: "App-Prefs:root=Privacy&path=Photos")
                let url1 = URL.init(string: UIApplicationOpenSettingsURLString)
                if #available(iOS 11, *) {
                    if UIApplication.shared.canOpenURL(url1!) {
                        UIApplication.shared.openURL(url1!)
                    }
                }else{
                    if UIApplication.shared.canOpenURL(url!) {
                        if #available(iOS 10, *) {
                            UIApplication.shared.open(url!, options:[:], completionHandler: nil)
                        }else{
                            UIApplication.shared.openURL(url!)
                        }
                    }
                }
            })
        }
    }
    
    func checkPhoto(authorizedBlock: @escaping () -> (), deniedBlock:  @escaping () -> ()) {
        let authStatus = PHPhotoLibrary.authorizationStatus()
        
        // .notDetermined .authorized .restricted .denied
        if authStatus == .notDetermined {
            // 第一次触发授权 alert
            PHPhotoLibrary.requestAuthorization { (status:PHAuthorizationStatus) -> Void in
                self.checkPhoto(authorizedBlock: authorizedBlock, deniedBlock: deniedBlock)
            }
        } else if authStatus == .authorized {
            Utils.DispatchAfter(after: 0.5, handler: {
                authorizedBlock()
            })
        } else {
            Utils.DispatchAfter(after: 0.5, handler: {
                deniedBlock()
            })
            
        }
    }
    
    @objc func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            print("错误")
            return
        }
        self.isScreenHot = false
        self.tableView.reloadData()
        PKhud.showText(text: "报表生成成功，请在相册中查看~")
    }
    
    func getOrderStatisDetail(){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.orderStatisDetail.rawValue, parameters: ["id":self.id,"startTime":self.startTime,"endTime":self.endTime]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if let array = [ListModel].deserialize(from: result["data"] as? [Any]) as? [ListModel]{
                    self.dataArray = array
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 2
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if section == 0 {
            return 1
        }
        return self.isScreenHot ? self.dataArray.count + 1 : self.dataArray.count
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 100
        }
        return self.isScreenHot ? 44 : 70
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SingleGoodsTableViewCell", for: indexPath) as! SingleGoodsTableViewCell
            cell.reload(withGoodsImage: self.img, name: self.name, startTime: self.startTime, endTime: self.endTime, array: self.dataArray)
            return cell
        }else{
            
            if self.isScreenHot {
                let cell = tableView.dequeueReusableCell(withIdentifier: "OrderStatisticsTableViewCell",for:indexPath) as! OrderStatisticsTableViewCell
                if indexPath.row == 0 {
                    cell.reload(withName:"品名", count: "累计采购量", money: "合计金额")
                }else{
                    let money = self.dataArray[indexPath.row - 1].price * Double(self.dataArray[indexPath.row - 1].num)
                    cell.reload(withName: self.dataArray[indexPath.row - 1].goods!.name, count: "\(self.dataArray[indexPath.row - 1].num)", money: "\(money)")
                }
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "SingleDetailTableViewCell", for: indexPath) as! SingleDetailTableViewCell
                cell.reload(withModel: self.dataArray[indexPath.row])
                return cell
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    

}
